package roborl;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Vector;

import roborl.snakeBot.SnakeRobot;
import roborl.triaLegRobo.ThreeLegMonster;

public class Elimination {

	static Vector<PhysRobot> bots;

	public static void addBots(int number, PhysicsWorld physicsWorld) {
		for (int i = 0; i < number; i++) {
//			PhysRobot physRobot = new ThreeLegMonster();
			PhysRobot physRobot = new SnakeRobot();
			bots.add(physRobot);
			physRobot.autoSave = false;
			physicsWorld.addRobot(physRobot);
		}
	}

	public static int checkMaxAchive() {
		int max = -1;
		for (PhysRobot physRobot : bots) {
			if (physRobot.achieve > max)
				max = physRobot.achieve;
		}
		return max;
	}

	public static void eliminate(double amount) {
		int amnt = (int) (amount * bots.size());

		PhysRobot physRobot[] = new PhysRobot[bots.size()];
		bots.toArray(physRobot);
		Arrays.sort(physRobot, new Comparator<PhysRobot>() {

			@Override
			public int compare(PhysRobot o1, PhysRobot o2) {
				// TODO Auto-generated method stub
				return o1.achieve - o2.achieve;
			}

		});
		for (int i = 0; i < amnt; i++) {
			physicsWorld.removeRobot(physRobot[i]);
			bots.remove(physRobot[i]);
		}
	}

	public static void resetAchive() {
		for (PhysRobot physRobot : bots) {
			physRobot.achieve = 0;
			physRobot.randomRate = 0.5f;
			physRobot.cRate*=0.6f;
			physRobot.init();
		}
	}

	static PhysicsWorld physicsWorld;

	public static void main(String s[]) throws InterruptedException {
		physicsWorld = new PhysicsWorld();
		bots = new Vector<PhysRobot>();
		// PhysRobot physRobot = new ThreeLegMonster();
		// physRobot.readOnly=true;
		new Thread() {
			public void run() {
				physicsWorld.start();
			}
		}.start();
		physicsWorld.target = 1;
		// physRobot.read();
		Thread.sleep(1000);
		addBots(10, physicsWorld);
		new Thread() {
			public void run() {
				while (true) {
					if (checkMaxAchive() > 5) {

						eliminate(0.5);
						resetAchive();
						if (bots.size() == 1) {
							System.out.println("Winner !");
							bots.get(0).store();
							break;
						}

						// addBots(5, physicsWorld);
					}
					try {
						Thread.sleep(10000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}.start();
	}
}
